<template>
	<el-dialog :title="dialogTitle" :visible.sync="visible" append-to-body width="560px">
		<el-form ref="form" size="medium" :model="dictFrom" :rules="dictRules" label-width="90px" class="dict_form_wrapper">
			<el-form-item label="字典名称" prop="content">
				<el-input v-model="dictFrom.content"></el-input>
			</el-form-item>
			<el-form-item label="字典编码" prop="code">
				<el-input v-model="dictFrom.code"></el-input>
			</el-form-item>
			<el-form-item label="字典描述">
				<el-input type="textarea" v-model="dictFrom.name"></el-input>
			</el-form-item>
			<el-row>
				<el-col :span="12">
					<el-form-item label="字典类型" prop="type">
						<el-radio-group v-model="dictFrom.type">
							<el-radio label="1">枚举</el-radio>
							<el-radio label="2">常量</el-radio>
						</el-radio-group>
					</el-form-item>
				</el-col>
				<el-col :span="12">
					<el-form-item label="是否可配置">
						<el-switch v-model="dictFrom.isConfig" active-value="1" inactive-value="2"></el-switch>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="显示类型" v-if="dictFrom.isConfig === '1'">
				<el-select v-model="showType" placeholder="请选择显示类型">
					<el-option label="数字(Number)" value="1"></el-option>
					<el-option label="开关(Switch)" value="2"></el-option>
					<el-option label="枚举(Enumerate)" value="3"></el-option>
					<el-option label="单选(Radio)" value="4"></el-option>
					<el-option label="文本(Text)" value="5"></el-option>
					<el-option label="文本(TextArea)" value="6"></el-option>
				</el-select>
				<template v-if="showType === '2'">
					<div class="show_type_switch">
						<dl>
							<dt>开启：</dt>
							<dd><el-input v-model="switchData.active"></el-input></dd>
						</dl>
						<dl>
							<dt>关闭：</dt>
							<dd><el-input v-model="switchData.inactive"></el-input></dd>
						</dl>
					</div>
				</template>
				<template v-if="showType === '4'">
					<el-button style="margin-left: 10px" type="text" @click="handleAddOption()">添加选项</el-button>
					<div class="show_type_option">
						<dl v-for="(item, index) in optionList" :key="index">
							<dt><el-input v-model="item.label"></el-input></dt>
							<dd class="val"><el-input v-model="item.value"></el-input></dd>
							<dd class="upload"><img-upload v-model="item.img"></img-upload></dd>
							<dd class="btn"><el-button type="text" @click="handleDelOption(index)">删除</el-button></dd>
						</dl>
					</div>
				</template>
			</el-form-item>
		</el-form>
		<template slot="footer">
			<el-button size="medium" @click="visible = false">取消</el-button>
			<el-button size="medium" type="primary" :loading="btnLoading" @click="handleSubmitForm">{{ addOrEdit ? '新增' : '修改' }}</el-button>
		</template>
	</el-dialog>
</template>

<script>
import imgUpload from './upload';
import { addedDictDefine, updateDictDefine } from '@/api/system/tbSysDictDefinition';
export default {
	components: { imgUpload },
	props: {
		value: {
			type: Boolean,
			default: false
		},
		dictData: {
			type: Object,
			default() {
				return {};
			}
		}
	},
	data() {
		return {
			visible: this.value,
			dictFrom: {},
			dictRules: {
				content: [{ required: true, message: '请输入字典名称', trigger: 'blur' }],
				code: [{ required: true, message: '请输入字典编码', trigger: 'blur' }],
				type: [{ required: true, message: '请选择字典类型', trigger: 'change' }]
			},
			btnLoading: false,
			showType: '',
			switchData: {},
			optionList: []
		};
	},
	computed: {
		addOrEdit() {
			return Object.keys(this.dictData).length === 0;
		},
		dialogTitle() {
			return `${this.addOrEdit ? '新增' : '修改'}字典定义`;
		}
	},
	watch: {
		value(flag) {
			this.visible = flag;
		},
		visible(flag) {
			this.$emit('input', flag);
			if (!flag) return false;
			this.$nextTick(() => {
				this.$refs['form'].resetFields();
				this.dictFrom = this.addOrEdit ? {} : { ...this.dictData };
				this.echoTypeOptions(this.dictFrom);
			});
		}
	},
	methods: {
		//回显选项
		echoTypeOptions(data) {
			let datas = !data.configJson ? null : JSON.parse(data.configJson);
			if (!datas) return false;
			this.switchData = {};
			this.optionList = [];
			this.showType = datas.type;
			if (this.showType === '2') {
				this.switchData = datas.switch;
			} else if (this.showType === '4') {
				this.optionList = datas.options;
			}
		},

		handleSubmitForm() {
			this.$refs['form'].validate(async (valid) => {
				if (!valid) return false;
				this.btnLoading = true;
				await this.submitFormRequest();
				this.btnLoading = false;
			});
		},

		//格式化请求参数
		formatRequestParams() {
			let params = { ...this.dictFrom, dictId: this.dictId };
			if (params.isConfig === '1') {
				let obj = { type: this.showType };
				if (this.showType === '2') {
					obj['switch'] = this.switchData;
				} else if (this.showType === '4') {
					if (!this.optionList.some((n) => !!n.img)) {
						obj['options'] = this.optionList.map((item) => {
							let obj = { ...item };
							this.$delete(obj, 'img');
							return obj;
						});
					} else {
						obj['options'] = this.optionList.map((item) => {
							let obj = { ...item };
							this.$set(obj, 'img', !item.img ? '' : item.img);
							return obj;
						});
					}
				}
				params['configJson'] = JSON.stringify(obj);
			} else {
				this.$delete(params, 'configJson');
			}
			return params;
		},

		//添加/修改枚举请求
		async submitFormRequest() {
			let params = this.formatRequestParams();
			let requestFun = eval(this.addOrEdit ? addedDictDefine : updateDictDefine);
			let result = await requestFun(params).then((res) => res.data);
			if (result.code === '0') {
				this.$emit('refresh');
				this.visible = false;
				this.$showCustomMessage('success', `${this.addOrEdit ? '新增' : '修改'}枚举成功`);
			}
		},

		//添加选项
		handleAddOption() {
			this.optionList.push({ label: '', value: '' });
		},

		//删除选项
		handleDelOption(index) {
			this.$delete(this.optionList, index);
		}
	}
};
</script>

<style lang="scss" scoped>
.dict_form_wrapper {
	width: 100%;
	padding: 10px 6px 0 0;
	box-sizing: border-box;
}

.show_type_switch {
	display: flex;
	align-items: center;
	margin-top: 10px;

	dl {
		display: flex;
		flex: 1;
		overflow: hidden;
	}

	dt {
		flex-shrink: 0;
	}

	dd {
		width: 100px;
	}
}

.show_type_option::v-deep {
	width: 100%;
	clear: both;
	margin-top: 10px;

	dl {
		display: flex;
		border: solid 1px #dcdfe6;
		border-top: none;

		&:first-child {
			border-top: solid 1px #dcdfe6;
		}
	}

	dt {
		flex: 1;
	}

	dd {
		flex-shrink: 0;
		border-left: solid 1px #dcdfe6;
		text-align: center;

		&.val {
			width: 80px;
		}

		&.upload {
			width: 80px;
		}

		&.btn {
			width: 50px;
		}
	}

	.el-input {
	}

	.el-input__inner {
		border: none;
		border-radius: 0;
	}
}
</style>
